package com.xk.school_device.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.xk.school_device.common.Result;
import com.xk.school_device.entity.Menus;
import com.xk.school_device.entity.Roles;
import com.xk.school_device.entity.Users;
import com.xk.school_device.mapper.UsersMapper;
import com.xk.school_device.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xk.school_device.utlis.MinioUtil;
import com.xk.school_device.utlis.PasswordUtil;
import io.minio.errors.MinioException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xk.school_device.common.UserContext;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xk
 * @since 2025-04-16
 */
@Service
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    private UsersMapper usersMapper;
    private static final Logger logger = LoggerFactory.getLogger(UsersServiceImpl.class);

    @Autowired
    private MinioUtil minioUtil;
    @Override
    public Result login(Users user) {
        Users users = usersMapper.selectOneByUserName(user.getUsername());
        if (users != null) {
            if (PasswordUtil.check(user.getPassword(), users.getPassword())) {
                StpUtil.login(users.getUserId());
                List<Menus> menusByRoleId = UserContext.menuService.getMenusByRoleId(users.getRoleId());
                List<Roles> rolesByRoleId = UserContext.roleService.getRolesByRoleId(users.getRoleId());
                logger.info("Roles for user {}: {}", users.getRoleId(), rolesByRoleId);
                users.setMenus(menusByRoleId);
                logger.info("Menus for user {}: {}", users.getRoleId(), menusByRoleId);
                users.setRoles(rolesByRoleId);
                String tokenValue = StpUtil.getTokenValue();
                users.setToken(tokenValue);
                return Result.success(users);
            }
        }
        return Result.failure("用户名或密码错误");
    }

    @Override
    public Result logout(Users user) {
        StpUtil.logout();
        return Result.success("退出成功");
    }

    @Override
    public Result updateUserInfoById(Users user) {
        usersMapper.updateUserInfoById(user);
        return Result.success("更新成功");
    }

    @Override
    public Result updateAvatar(String id, MultipartFile file) {
        try {
            String imgUrl = minioUtil.upload(file);
            Users byId = usersMapper.selectUsersById(id);
            try{
                if (byId.getImgUrl() != null && !byId.getImgUrl().isEmpty()) {
                    minioUtil.delete(byId.getImgUrl());
                }
            } catch (Exception e){
                logger.info("图片不存在");
            }

            byId.setImgUrl(imgUrl);
            usersMapper.updateByIdImage(byId);
            return Result.success("更新成功");
        } catch (MinioException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void restPassword(String id, String password) {
        usersMapper.restPassword(id,PasswordUtil.encrypt(password));
    }

    @Override
    public Result getUser(Users user) {
        List<Users> users=usersMapper.getUser(user);
        return Result.success(users);
    }
}
